// AuthController.java
package com.team06.login.controller;

import com.team06.login.entity.User;
import com.team06.login.service.UserService;
import com.team06.service.EmailService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.Random;

@Slf4j
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {
    private final UserService userService;
    private final PasswordEncoder passwordEncoder;
    private final EmailService emailService;
    private final CacheManager cacheManager;
    // 添加邮箱检查接口
    @PostMapping("/check-email")
    public ResponseEntity<?> checkEmail(@RequestBody Map<String, String> request) {
        String email = request.get("email");
        boolean exists = userService.existsByEmail(email);
        return ResponseEntity.ok(Map.of("exists", exists));
    }
    // AuthController.java
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody RegisterRequest request) {
        // 检查邮箱是否已存在
        if (userService.existsByEmail(request.getEmail())) {
            return ResponseEntity.badRequest().body(Map.of(
                    "message", "邮箱已被注册",
                    "status", "error",
                    "field", "email"
            ));
        }

        // 检查用户名是否已存在
        if (userService.existsByUsername(request.getUsername())) {
            return ResponseEntity.badRequest().body(Map.of(
                    "message", "用户名已被使用",
                    "status", "error",
                    "field", "username"
            ));
        }

        try {
            User user = new User();
            user.setUsername(request.getUsername());
            user.setEmail(request.getEmail());
            user.setPhone(request.getPhone());
            user.setGender(request.getGender());
            user.setPassword(passwordEncoder.encode(request.getPassword()));
            user.setEnabledStatus(1);

            userService.save(user);

            return ResponseEntity.ok(Map.of(
                    "message", "注册成功",
                    "status", "success"
            ));
        } catch (Exception e) {
            log.error("注册失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                    "message", "注册失败，请稍后重试",
                    "status", "error"
            ));
        }
    }
    @PostMapping("/forgot-password")
    public ResponseEntity<?> forgotPassword(@RequestBody ForgotPasswordRequest request) {
        log.info("处理忘记密码请求 - 开始, 邮箱: {}", request.getEmail());
        log.info("收到忘记密码请求，邮箱: {}", request.getEmail());
        try {
            // 验证邮箱是否存在
            User user = userService.findByEmail(request.getEmail());
            if (user == null) {
                log.warn("邮箱未注册: {}", request.getEmail());
                return ResponseEntity.badRequest().body(Map.of(
                        "message", "该邮箱未注册",
                        "status", "error",
                        "email", request.getEmail()
                ));
            }

            // 生成随机验证码
            String verificationCode = String.format("%06d", new Random().nextInt(999999));
            log.info("生成验证码成功 - 邮箱: {}, 验证码: {}", request.getEmail(), verificationCode);

            // 存储到缓存
            try {
                cacheManager.getCache("verificationCodes").put(
                        request.getEmail(),
                        new VerificationCache(verificationCode, LocalDateTime.now().plusMinutes(15))
                );
                log.info("验证码已缓存 - 邮箱: {}", request.getEmail());
            } catch (Exception e) {
                log.error("缓存验证码失败 - 邮箱: {}", request.getEmail(), e);
                return ResponseEntity.internalServerError().body(Map.of(
                        "message", "系统错误，请稍后重试",
                        "status", "error"
                ));
            }

            // 发送邮件
            try {
                emailService.sendVerificationCodeEmail(request.getEmail(), verificationCode);
                log.info("邮件发送请求已完成 - 邮箱: {}", request.getEmail());
                return ResponseEntity.ok(Map.of(
                        "message", "验证码已发送至您的邮箱",
                        "status", "success",
                        "email", request.getEmail()
                ));
            } catch (Exception e) {
                log.error("邮件发送失败 - 邮箱: {}", request.getEmail(), e);
                return ResponseEntity.internalServerError().body(Map.of(
                        "message", "邮件发送失败，请检查邮箱地址或稍后重试",
                        "status", "error",
                        "detail", e.getMessage()
                ));
            }
        } catch (Exception e) {
            log.error("处理忘记密码请求时发生未知错误 - 邮箱: {}", request.getEmail(), e);
            return ResponseEntity.internalServerError().body(Map.of(
                    "message", "系统错误，请稍后重试",
                    "status", "error"
            ));
        }
    }
    @PostMapping("/reset-password")
    public ResponseEntity<?> resetPassword(@RequestBody ResetPasswordRequest request) {
        log.info("处理密码重置请求，邮箱: {}", request.getEmail());

        // 从缓存获取验证码
        VerificationCache cached = cacheManager.getCache("verificationCodes")
                .get(request.getEmail(), VerificationCache.class);

        // 验证验证码
        if (cached == null || !cached.getCode().equals(request.getVerificationCode())) {
            return ResponseEntity.badRequest().body(Map.of("message", "验证码错误或已过期"));
        }
        if (LocalDateTime.now().isAfter(cached.getExpiryTime())) {
            return ResponseEntity.badRequest().body(Map.of("message", "验证码已过期"));
        }

        // 更新密码
        User user = userService.findByEmail(request.getEmail());
        user.setPassword(passwordEncoder.encode(request.getNewPassword()));
        userService.updateById(user);

        // 清除缓存
        cacheManager.getCache("verificationCodes").evict(request.getEmail());

        return ResponseEntity.ok(Map.of("message", "密码重置成功"));
    }

    // 内部缓存数据结构
    @Data
    @AllArgsConstructor
    private static class VerificationCache {
        private String code;
        private LocalDateTime expiryTime;
    }

    // 请求DTO保持不变
    @Data
    static class ForgotPasswordRequest {
        private String email;
    }

    @Data
    static class ResetPasswordRequest {
        private String email;
        private String verificationCode;
        private String newPassword;
    }

    @Data
    static class RegisterRequest {
        private String username;
        private String email;
        private String password;
        private String phone;
        private String gender;
    }
}